const router = require('express').Router()
const pool = require('../db/pool.js')
const makeCapcha = require('../util/yzm.js')
const jwt = require('../token/token.js')

router.get('/consumer/email_yzm', async (req, res) => {
  let { email } = req.query

  // 生成随机数
  function rand(min, max) {
    return Math.random() * (max - min + 1) + min | 0 // 特殊的技巧，|0可以强制转换为整数，向下舍入
  }
  // 生成字符
  let p = 'ABCDEFGHKMNPQRSTUVWXYZ1234567890'
  let str = ''
  for (var i = 0; i < 4; i++) { // 生成4个字符
    str += p.charAt(Math.random() * p.length | 0)
  }

  //发送邮箱验证码
  const { SMTPClient } = await import('emailjs')
  const client = new SMTPClient({
    user: '2466564159@qq.com',
    password: 'ndinkocygwikeabg',
    host: 'smtp.qq.com',
    ssl: true,
  })
  await client.sendAsync({
    text: `你的验证码为：${str}`,
    from: '2466564159@qq.com',
    to: email,
    subject: '茶七网',
  })

  req.session.email_yzm = str
  res.end()
})

router.get('/consumer/yzm', (req, res) => {
  let img = makeCapcha()
  res.set({
    'Content-Type': 'image/bmp'
  })
  req.session.yzm = img.code
  res.end(img.getFileData())
})

router.post('/consumer/pwdLogin', async (req, res) => {
  let { email, pwd, yzm } = req.body
  let sql = `select * from consumer where email = '${email}' and pwd = ${pwd}`
  let result = await pool.query(sql)
  let consumer = result[0][0]

  if (yzm !== req.session.yzm) {
    res.status(500).json({
      msg: '验证码错误'
    })
  } else if (consumer) {
    //设置token
    let token = jwt.setToken(consumer)
    res.set({
      authorization: token
    })

    req.session.user = consumer
    res.status(200).json(consumer)
  } else {
    res.status(500).json({
      msg: '邮箱或密码错误'
    })
  }
})

router.post('/consumer/login', async (req, res) => {
  let { email, yzm, email_yzm } = req.body
  let sql = `select * from consumer where email = '${email}'`
  let result = await pool.query(sql)
  let consumer = result[0][0]

  if (yzm !== req.session.yzm) {
    res.status(500).json({
      msg: '验证码错误'
    })
  } else if (email_yzm !== req.session.email_yzm) {
    res.status(500).json({
      msg: '邮箱验证码错误'
    })
  } else if (consumer) {
    //设置token
    let token = jwt.setToken(consumer)
    res.set({
      authorization: token
    })

    req.session.user = consumer
    res.status(200).json(consumer)
  } else {
    res.status(500).json({
      msg: '邮箱错误'
    })
  }
})

router.post('/consumer/register', async (req, res) => {
  let { email, yzm, email_yzm, pwd } = req.body

  if (yzm !== req.session.yzm) {
    res.status(500).json({
      msg: '验证码错误'
    })
  } else if (email_yzm !== req.session.email_yzm) {
    res.status(500).json({
      msg: '邮箱验证码错误'
    })
  } else {
    let sql = `select * from consumer where email = '${ email }'`
    let result = await pool.query(sql)
    let consumer = result[0][0]
    if ( consumer ) {
      res.status(500).json({
        msg: '邮箱已注册'
      })
      return
    }

    sql = `insert into consumer (email, pwd, nickname, img_url) values ('${email}', '${pwd}', 'sb', '/img/consumer/1.png')`
    result = await pool.query(sql)

    sql = `select * from consumer where email = '${ email }'`
    result = await pool.query(sql)
    consumer = result[0][0]

    //设置token
    let token = jwt.setToken(consumer)
    res.set({
      authorization: token
    })

    req.session.user = consumer
    res.status(200).json(consumer)
  }
})

module.exports = router